<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <SearchForm
          v-show="showSearch"
          v-model="queryParams"
          :options="options.formOps"
          @onQuery="getList"
        ></SearchForm>
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              >新增</el-button
            >
          </el-col> -->

          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>
        <Table
          ref="table"
          :auto-featch="true"
          :fetch-data="fetchData"
          :options="options.table"
          actionWidth="100"
        >
          <template #beforehiddenLevel>
            <el-table-column
              label="装置"
              prop="deviceId"
              align="center"
              width="150"
              key="deviceId"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ columnZz(row.deviceId) }}
              </template>
            </el-table-column>
            <el-table-column
              label="隐患分类"
              prop="hiddenType"
              align="center"
              width="150"
              key="hiddenType"
            >
            </el-table-column>
          </template>
          <template #afterhiddenRectificationMeasures>
            <el-table-column
              label="整改责任人"
              prop="rectificationUserName"
              align="center"
              width="159"
              key="rectificationUserName"
            >
            </el-table-column>

            <el-table-column
              label="复核人"
              width="150"
              prop="reviewUserName"
              align="center"
              key="reviewUserName"
            >
            </el-table-column>
          </template>

          <template #actionButton="{ row }">
            <el-button type="text" @click="handleEdit(row)">详情</el-button>

            <!-- <el-button
              type="text"
              icon="Delete"
              style="color: red"
              @click="handleDel(row)"
              >删除</el-button
            > -->
          </template></Table
        >
        <DialogVform
          :formJson="formJson"
          ref="dialogVform"
          :slots="[
            'deptSlot',
            'typeSlot',
            'sonTypeSlot',
            'rectificationUserId',
            'reviewUserId',
            'fileSlot',
            'deviceId',
          ]"
          @onSubmit="onSubmit"
          title="隐患登记"
          :showButton="false"
        >
          <template #deviceId>
            <el-form-item label="装置" label-position="right">
              <el-select style="width: 100%" v-model="form.deviceId">
                <el-option
                  v-for="it in zzData"
                  :value="it.id"
                  :label="it.deviceName"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
          <template #deptSlot>
            <el-form-item label="部门" prop="deptId" label-position="right">
              <TreeSelect
                v-model="form.deptId"
                :options="deptTree"
                @change="changeDept"
                style="width: 100%"
              ></TreeSelect>
            </el-form-item>
          </template>
          <template #fileSlot>
            <el-form-item label="文件上传" prop="fileId">
              <ImgList :imgs="files"></ImgList>
              <!-- 
              <FileUpload
                :limit="1"
                :fileSize="30"
                :fileType="['png', 'jpeg', 'jpg']"
                v-model="files"
              ></FileUpload> -->
            </el-form-item>
          </template>
          <template #typeSlot>
            <el-form-item label="隐患分类" label-position="right">
              <el-select
                @change="changeHiddenType"
                style="width: 100%"
                v-model="form.hiddenType"
              >
                <el-option value="安全"></el-option>
                <el-option value="设备"></el-option>
                <el-option value="工艺"></el-option>
                <el-option value="操作"></el-option>
                <el-option value="电气"></el-option>
                <el-option value="仪表"></el-option>
                <el-option value="消防"></el-option>
                <el-option value="总图"></el-option>
                <el-option value="其他"></el-option>
              </el-select>
            </el-form-item>
          </template>

          <template #rectificationUserId>
            <el-form-item
              label="整改责任人"
              prop="rectificationUserId"
              label-position="right"
            >
              <el-input
                v-model="form.rectificationUserName"
                readonly
                @click="onInnerOpen('rectificationUser')"
              ></el-input>
            </el-form-item>
          </template>
          <template #reviewUserId>
            <el-form-item
              label="复核人"
              prop="reviewUserId"
              label-position="right"
            >
              <el-input
                v-model="form.reviewUserName"
                readonly
                @click="onInnerOpen('reviewUser')"
              ></el-input>
            </el-form-item>
          </template>

          <TableSelect
            ref="userTableSelect"
            :queryApi="listUser"
            :options="[]"
            :rowKey="'userId'"
            rowLabel="nickName"
            @onConfirm="onUserConfirm"
            rowLabelText="用户昵称"
            :maxNum="1"
          >
            <template #formSlot="{ handleQuery, filterForm }">
              <el-col :span="8">
                <el-form-item label="部门名称">
                  <el-input
                    size="small"
                    @change="handleQuery"
                    v-model="filterForm.deptName"
                    clearable
                    style="width: 100%"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="用户名称">
                  <el-input
                    size="small"
                    @change="handleQuery"
                    v-model="filterForm.userName"
                    clearable
                    style="width: 100%"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
              </el-col>
            </template>
            <template #tableSlot>
              <el-table-column
                label="部门"
                align="center"
                key="deptName"
                prop="dept.deptName"
              />
              <el-table-column
                label="用户名称"
                align="center"
                key="userName"
                prop="userName"
              />
              <el-table-column
                label="用户昵称"
                align="center"
                key="nickName"
                prop="nickName"
              />
            </template>
          </TableSelect>
        </DialogVform>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import Table from "@/components/Table/index.vue";
import SearchForm from "@/components/searchForm/index";
import DialogVform from "@/components/dialogVform/index";
import formJson from "./components/options.json";
import { apis as APIS } from "@/api/yhpc/yhdj.js";
import { parseTime } from "@/utils/ruoyi.js";
import { useAsyncData, useFormJson } from "@/views/hooks/useAsyncData.js";
import { deptTreeSelect, listUser } from "@/api/system/user";
import FileUpload from "@/components/FileUpload";
import { selectOptions } from "./components/consts";
import TableSelect from "@/components/tableSelect/index";
import ImgList from "@/components/ImgList";

const { proxy } = getCurrentInstance();
const ops = useFormJson(formJson, {
  sort: [],
  sortable: [],
});

const options = reactive({
  table: ops,
  formOps: ops.filter((i) =>
    ["hiddenSource", "hiddenType", "hiddenLevel", "hiddenCheckType"].includes(
      i.prop
    )
  ),
});
const files = ref([]);
const showSearch = ref(true);
const dialogVform = ref();
const deptTree = ref([]);
const table = ref();
const editRow = ref({});
const sonTypes = ref([]);
const userType = ref("");
const userTableSelect = ref();
const changeHiddenType = (val) => {
  sonTypes.value = selectOptions[val] || [];
};
const zzData = ref([]);
const getZzSelect = () => {
  APIS.zz().then((res) => {
    zzData.value = res.rows;
  });
};
const columnZz = (id) => {
  return zzData.value.find((item) => item.id == id)?.deviceName;
};
const changeDept = (val, label) => {
  form.value.deptName = label;
  form.value.deptId = val;
};
const plugEdit = (row) => {
  form.value.hiddenImageFileName = row.hiddenImageFileName;
  form.value.hiddenImageFileId = row.hiddenImageFileId;
  form.value.hiddenImageFileUrl = row.hiddenImageFileUrl;
  form.value.hiddenType = row.hiddenType;
  form.value.hiddenBelongType = row.hiddenBelongType;
  form.value.deptName = row.deptName;
  form.value.deptId = row.deptId;
  form.value.rectificationUserId = row.rectificationUserId;
  form.value.rectificationUserName = row.rectificationUserName;
  form.value.reviewUserId = row.reviewUserId;
  form.value.reviewUserName = row.reviewUserName;
  editRow.value = { ...row };
  if (row.hiddenImageFileId) {
    files.value = [
      {
        name: row.hiddenImageFileName,
        id: row.hiddenImageFileId,
        url: row.hiddenImageFileUrl,
      },
    ];
  }
};

const plugAdd = () => {
  return {
    hiddenCheckUser: JSON.parse(localStorage.getItem("USER_INFO")).userName,
    hiddenCheckTime: parseTime(new Date()),
  };
};
const onInnerOpen = (type) => {
  userType.value = type;
  const {
    rectificationUserId,
    rectificationUserName,
    reviewUserId,
    reviewUserName,
  } = form.value;
  let values =
    (rectificationUserId && (rectificationUserId + "").split(",")) || [];
  let names = (rectificationUserName && rectificationUserName.split(",")) || [];
  if (type == "reviewUser") {
    values = (reviewUserId && reviewUserId.split(",")) || [];
    names = (reviewUserName && reviewUserName.split(",")) || [];
  }

  userTableSelect.value.open(
    values.map((item, index) => ({
      value: values[index],
      label: names[index],
    }))
  );
};
const onUserConfirm = (data) => {
  const values = data.map((item) => item.value);
  const names = data.map((item) => item.label);
  if (userType.value == "reviewUser") {
    form.value.reviewUserId = values.join(",");
    form.value.reviewUserName = names.join(",");
  } else {
    form.value.rectificationUserId = values.join(",");
    form.value.rectificationUserName = names.join(",");
  }
};
const {
  onSubmit,
  fetchData,
  dialogType,
  handleAdd,
  handleEdit,
  getList,
  handleDel,
  queryParams,
  form,
} = useAsyncData({
  APIS,
  formJson,
  dialogVform,
  table,
  proxy,
  plugEdit,
  plugAdd,
  filterForm: {
    hiddenCheckUser: JSON.parse(localStorage.getItem("USER_INFO")).userName,
  },
});

watch(
  () => files,
  (newData) => {
    console.log(newData);
    if (newData.value.length === 0) {
      form.value.hiddenImageFileName = "";
      form.value.hiddenImageFileId = "";
      form.value.hiddenImageFileUrl = "";
    } else {
      form.value.hiddenImageFileName = newData.value[0].name;
      form.value.hiddenImageFileId = newData.value[0].id;
      form.value.hiddenImageFileUrl = newData.value[0].url;
    }
  },
  {
    deep: true,
  }
);
onMounted(() => {
  getZzSelect();
  deptTreeSelect().then((response) => {
    deptTree.value = response.data;
    console.log(deptTree.value);
  });
});
</script>

<style lang="scss" scoped>
::v-deep.el-form-item__label {
  text-align: right !important;
}
</style>
